<?php
class WebTemplateModel extends Model {
	var $_table = 'web_theme_template';
	
	var $template_id_nak; //INT UNSIGNED NOT NULL AUTO_INCREMENT,
	var $theme_id_nr; //INT NOT NULL COMMENT '主题',
	var $page_type_sr; //VARCHAR(16) NOT NULL COMMENT '内容模型',
	var $template_file_sr; //VARCHAR(256) NOT NULL COMMENT '模板文件'
	

	/**
	 * 
	 * 读取模板文件
	 */
	public static function getTemplateTreeData() {
		$id = 2;
		$tpls = array (array ('id' => 1, 'pId' => 0, 'tpl' => '', 'name' => '系统模板', 'isParent' => true, 'open' => true ) );
		self::_readTemplateFiles ( TEMPLATE_PATH, $tpls, 1, $id );
		return $tpls;
	}
	
	/**
	 * 
	 * 获取主题中对应页面类型的模板文件
	 * @param string $page_type 页面类型
	 * @param mixed $theme 主题，不指定时，读取默认主题
	 * @return mixed 未找到模板文件时返回false
	 */
	public function getTemplateFile($page_type, $theme = null) {
		$where ['page_type'] = $page_type;
		if (empty ( $theme )) {
			$where ['TM.selected'] = 1;
		} else {
			$where ['TM.name'] = $theme;
		}
		$this->alias ( 'TPL' );
		$this->join ( 'web_theme AS TM', "TPL.theme_id = TM.theme_id" );
		$tpl = $this->get ( 'template_file', $where );
		return $tpl;
	}
	/**
	 * 
	 * 读取模板文件
	 * @param string $dir
	 * @param array $tpls
	 * @param int $pid
	 * @param int $id
	 */
	private static function _readTemplateFiles($dir, &$tpls, $pid, &$id) {
		static $reversed_tpls = array('404.tpl','sitemap.tpl','error.tpl','rss.tpl');
		$dh = opendir ( $dir );
		$tdir = str_replace ( TEMPLATE_PATH, '', $dir );
		if ($dh) {
			while ( ($file = readdir ( $dh )) !== false ) {
				if (preg_match ( '#^\.#', $file )) {
					continue;
				}
				if (is_dir ( $dir . '/' . $file ) && ! preg_match ( '/^(image|images|css|imgs|img|style|js|scripts|media)$/i', $file )) {
					$id = $id + 1;
					$tpls [] = array ('id' => $id, 'pId' => $pid, 'dir' => $tdir, 'name' => $file, "isParent" => true );
					self::_readTemplateFiles ( $dir . '/' . $file, $tpls, $id, $id );
				} else if (preg_match ( '/\.tpl$/', $file ) && !in_array($file, $reversed_tpls)) {
					$id = $id + 1;
					$tpls [] = array ('id' => $id, 'pId' => $pid, 'dir' => $tdir, 'name' => $file );
				}
			}
			closedir ( $dh );
		}
	}
}